from django.shortcuts import render
from rest_framework.views import APIView
from . import serializers
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status
import base64
import pickle

# Create your views here.


class ShopCartView(APIView):
    # 重写认证方法,登录不登录都进来(传入JWT token,但是不指定权限)
    def perform_authentication(self, request):
        pass

    def get(self, request):
        pass

    def post(self, request):
        """
        创建序列化器,校验参数,并返回校验后的参数
        :param request:
        :return:
        """
        serializer = serializers.ShopCartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 登录用户见数据写入到redis
            # 创建redis对象
            redis_con = get_redis_connection('shopcart')
            pl = redis_con.pipeline()
            # 将sku_id 和 count 写入到hash
            pl.hincrby('shopcart_%s' % user.id, sku_id, count)
            # 将sku_id 写入set ,指定勾选

            pl.sadd('selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            # 读取cookie中的原有购物车数据
            cookies_cart_str = request.COOKIES.get('cart')
            if not cookies_cart_str:
                cookie_cart_dic = {}
            else:
                cookies_cart_str_bytes = cookies_cart_str.encode()
                cookies_cart_dict_bytes = base64.b64decode(cookies_cart_str_bytes)
                cookie_cart_dic = pickle.loads(cookies_cart_dict_bytes)
            # 判断字典中是否有sku_id,有则累加,无则直接赋值
            if sku_id in cookie_cart_dic:
                origin_count = cookie_cart_dic[sku_id]['count']
                count += origin_count
            cookie_cart_dic[sku_id] = {
                'count': count,
                'selected': selected
            }
            response = Response(serializer.data, status=status.HTTP_201_CREATED)
            # 将新的字典写入cookie
            new_cookies_cart_dict_bytes = pickle.dumps(cookie_cart_dic)
            new_cookies_cart_str_bytes = base64.b64encode(new_cookies_cart_dict_bytes)
            new_cookies_cart_str = new_cookies_cart_str_bytes.decode()

            response.set_cookie('cart', new_cookies_cart_str)
            return response

    def put(self, request):
        pass

    def delete(self, request):
        pass